<!-- <template>
  <div class="menu-demo">
    <a-menu
      :style="{ width: '200px', height: '100%' }"
      :selected-keys="['0']"
      :default-selected-keys="['0']"
      show-collapse-button
    >
      <template v-for="(item, index) in props.getRoutes" :key="item.order">
        <template v-if="item.children && !item.meta">
          <a-menu-item :key="item.order">{{
            item.children[0].meta.locale
          }}</a-menu-item>
        </template>
        <template v-else>
          <a-sub-menu key="item.order">
            <template #icon><icon-apps></icon-apps></template>
            <template #title>{{ item.meta?.locale }}</template>
          </a-sub-menu>
        </template>
      </template>
    </a-menu>
  </div>
</template> -->
<script lang="tsx">
import {
  defineComponent,
  computed,
  reactive,
  ref,
  h,
  compile,
  toRefs,
} from "vue";

import { useRoute, useRouter, RouteRecordRaw } from "vue-router";
import type { RouteMeta } from "vue-router";
import { openWindow, regexUrl } from "@/untils/index";
  import { listenerRouteChange } from '@/untils/route-listener';
interface MenuItemProps {
  customBtnFunc?: Function | null;
  btnShow?: boolean | false;
}

export default defineComponent({
  emit: [""],
  setup(props: MenuItemProps,ctx) {
    const route = useRoute();
    const router = useRouter();
    const getRoutes: RouteRecordRaw[] = global.antRouter;
    const selectedKey = ref<any>([]);
    const topMenu = ref<string>('horizontal');
      const openKeys = ref<string[]>([]);
    const goto = (item: RouteRecordRaw) => {
      // Open external link
      // console.log(item);
      
      if (regexUrl.test(item.path)) {
        openWindow(item.path);
        selectedKey.value = [item.name as string];
        return;
      }
      // Eliminate external link side effects
      const { hideInMenu, activeMenu } = item.meta as RouteMeta;
      if (route.name === item.name && !hideInMenu && !activeMenu) {
        selectedKey.value = [item.name as string];
        return;
      }
      // Trigger router change
      router.push({
        name: item.name
      });
    };
    const findMenuOpenKeys = (target: string) => {
        const result: string[] = [];
        let isFind = false;
        const backtrack = (item: RouteRecordRaw, keys: string[]) => {
          if (item.name === target) {
            isFind = true;
            result.push(...keys);
            return;
          }
          if (item.children?.length) {
            item.children.forEach((el:any) => {
              backtrack(el, [...keys, el.name as string]);
            });
          }
        };
        getRoutes.forEach((el: RouteRecordRaw) => {
          if (isFind) return; // Performance optimization
          backtrack(el, [el.name as string]);
        });
        return result;
      };
      listenerRouteChange((newRoute) => {
        const { requiresAuth, activeMenu, hideInMenu } = newRoute.meta;
        if (requiresAuth && (!hideInMenu || activeMenu)) {
          const menuOpenKeys = findMenuOpenKeys(
            (activeMenu || newRoute.name) as string
          );

          const keySet = new Set([...menuOpenKeys, ...openKeys.value]);
          openKeys.value = [...keySet];
          
          selectedKey.value = [
            activeMenu || menuOpenKeys[menuOpenKeys.length - 1],
          ];
        }
      }, true);
    const renderMenu = () => {
      function travel(_route: RouteRecordRaw[], nodes = []) {
        if (_route) {
          _route.forEach((element) => {
            // This is demo, modify nodes as needed
            const icon = element?.meta?.icon
              ? () => h(compile(`<${element?.meta?.icon}/>`))
              : null;
            const node =
              element?.children && element?.children.length !== 0 &&element?.meta?.locale!==element?.children[0].meta?.locale ? (
                <a-sub-menu
                  key={element?.name}
                  v-slots={{
                    icon,
                    title: () => h(compile(`${element?.meta?.locale || ""}`)),
                  }}
                >
                  {travel(element?.children)}
                </a-sub-menu>
              ) : (
                <a-menu-item
                  key={element?.name}
                  v-slots={{ icon }}
                  onClick={() => goto(element)}
                >
                  {element?.meta?.locale || ""}
                </a-menu-item>
              );
            nodes.push(node as never);
          });
        }
        return nodes;
      }
      return travel(getRoutes);
    };
    return () => (
      <a-menu
        defaultOpenKeys={openKeys.value}
        defaultSelectedKeys={selectedKey.value}
        style={{ width: 200, height: '100%' }}
        hasCollapseButton
      >
        {renderMenu()}
      </a-menu>
    );
  },
});
</script>
<style scoped lang="less">
// .menu-demo {
//   box-sizing: border-box;
//   width: 200px;
//   border-right: 1px solid var(--color-neutral-3);
//   height: 100%;
//   //   padding: 40px;
//   background-color: var(--color-neutral-2);
// }
.menu-demo .arco-menu-inner {
  overflow-y: auto;
}
</style>
